class_name Afterimage extends Polygon2D
@export var points:PackedVector2Array
@export_range(1,100) var length:int
@export_range(1,100) var smooth:int=1
@export var trail_color: Array[Gradient] # 颜色渐变
var old_transform:Transform2D
@export var sword: Node2D

var target_transform: Transform2D
var original_trail_color: Array[Gradient]
var is_color_changed: bool = false
var trail_points: PackedVector2Array = [] # 存储拖尾的顶点

func _ready() -> void:
	# 保存原始颜色
	original_trail_color = trail_color.duplicate()
	colored(trail_color)
	
func get_total_length()->int:
	return length*smooth
	
func _enter_tree():
	# 初始化拖尾顶点数组
	trail_points.resize(get_total_length() * points.size())
	
func colored(gradients:Array[Gradient]):
	var array:PackedColorArray=[]
	var size=get_total_length()
	for i in size:
		var j=float(i)/(size-1)
		for gradient in gradients:
			array.append(gradient.sample(j))
	vertex_colors=array

## 改变轨迹颜色
func change_trail_color(new_color: Color, duration: float) -> void:
	# 创建新的渐变颜色
	var new_gradients: Array[Gradient] = []
	for gradient in trail_color:
		var new_gradient = Gradient.new()
		var colors = PackedColorArray()
		colors.append(new_color)
		colors.append(new_color)
		new_gradient.colors = colors
		new_gradients.append(new_gradient)
	
	# 应用新颜色
	trail_color = new_gradients
	colored(trail_color)
	is_color_changed = true
	
	# 持续时间后恢复原色
	await get_tree().create_timer(duration).timeout
	restore_original_color()

## 恢复原始颜色
func restore_original_color() -> void:
	if is_color_changed:
		trail_color = original_trail_color.duplicate()
		colored(trail_color)
		is_color_changed = false
	
func _physics_process(_delta):
	## 如果不在攻击，取之前的target_transform
	target_transform = sword.transform
	transform = target_transform.affine_inverse()
	var array:PackedVector2Array=[]
	for i in smooth:
		var new_transform:=target_transform.interpolate_with(old_transform,float(i)/smooth)
		array.append_array(new_transform * points)
	old_transform=target_transform
	# 更新拖尾顶点
	trail_points = array.duplicate()
	# 设置多边形顶点
	polygon = trail_points
